/*
========================================================================
 Name        : ExportContactsSelectDirContainer.cpp
 Author      : etouch.cc
 Copyright   : etouch.cc,All Right Reserved!
 Description : 
========================================================================
*/
 
#include <barsread.h>
#include <stringloader.h>
#include <aknlists.h>
#include <eikenv.h>
#include <akniconarray.h>
#include <eikclbd.h>
#include <aknviewappui.h>
#include <eikappui.h>
#include <eiklabel.h>
#include <eikenv.h>
#include <gdi.h>
#include <eikedwin.h>
#include <ExportContacts.rsg>
#include <ExportContacts.mbg>
#include <GULICON.H>
#include <UTF.H>
#include <aknglobalnote.h> 

#include "ExportContactsSelectDirContainer.h"
#include "ExportContactsSelectDirContainerView.h"
#include "ExportContacts.hrh"
#include "ExportContactsListBox.hrh"
#include "ExportContactsSelectDirContainer.hrh"
#include "CDirLinkList.h"
#include "ExportContactsAppUi.h"

//consts
_LIT(KPhoneDisk,"C:\\");
_LIT(KDDriver,"D:\\");
_LIT(KMemoryCardDisk,"E:\\");
_LIT(KSlash,"\\");
_LIT(KFileName,"C:\\CELog.txt");

_LIT(KExportContactsFile, "\\resource\\apps\\ExportContacts.mbm" );
_LIT(KExportFileExtension,".csv");
const TInt KExportFileExtensionLength = 4;
 
CExportContactsSelectDirContainer::CExportContactsSelectDirContainer()
{ 
	iFileInputLabel = NULL;
	iFileInputEdit = NULL;
	iFileExtensionLabel = NULL;
	iListBox = NULL;	 
	iExportFileFullName = NULL;
	iDirLinkList = NULL;	
	iDir = NULL;
}
 
CExportContactsSelectDirContainer::~CExportContactsSelectDirContainer()
{
	iFs.Close();
	if(iFileInputLabel)
	{
		delete iFileInputLabel;
		iFileInputLabel = NULL;
	}
	if(iFileInputEdit)
	{
		delete iFileInputEdit;
		iFileInputEdit = NULL;
	}	
	if(iFileExtensionLabel)
	{
		delete iFileExtensionLabel;
		iFileExtensionLabel = NULL;
	}
	if(iListBox)
	{
		delete iListBox;
		iListBox = NULL;
	} 	
	if(iBgContext)
	{
		delete iBgContext;
		iBgContext = NULL;
	}	 
	if(iExportFileFullName)
	{
		delete iExportFileFullName;
		iExportFileFullName = NULL;
	}
	if(iDir)
	{
		delete iDir;
		iDir = NULL;
	}
	if(iDirLinkList)
	{
		delete iDirLinkList;
		iDirLinkList = NULL;
	}	 
}
				
 
CExportContactsSelectDirContainer* CExportContactsSelectDirContainer::NewL( const TRect& aRect, 
																			const CCoeControl* aParent, 
																			MEikCommandObserver* aCommandObserver
																		   )
{
	CExportContactsSelectDirContainer* self = CExportContactsSelectDirContainer::NewLC( aRect, aParent, aCommandObserver );
	CleanupStack::Pop( self );
	return self;
}

 
CExportContactsSelectDirContainer* CExportContactsSelectDirContainer::NewLC( 
																			const TRect& aRect, 
																			const CCoeControl* aParent, 
																			MEikCommandObserver* aCommandObserver 
																		   )
{
	CExportContactsSelectDirContainer* self = new ( ELeave ) CExportContactsSelectDirContainer();
	CleanupStack::PushL( self );
	self->ConstructL( aRect, aParent, aCommandObserver );
	return self;
}
			
 
void CExportContactsSelectDirContainer::ConstructL( 
													const TRect& aRect,
													const CCoeControl* aParent, 
													MEikCommandObserver* aCommandObserver 
												  )
{
	if ( aParent == NULL )
	{
		CreateWindowL();
	}
	else
	{
	    SetContainerWindowL( *aParent );
	}
	iFs.Connect();
	
	iBgContext = CAknsBasicBackgroundControlContext::NewL( KAknsIIDQsnBgAreaMain,aRect,ETrue);
	
	iFocusControl = NULL;
	iCommandObserver = aCommandObserver;
	
	InitializeLinkList();
	InitializeControlsL();	
	
	SetRect( aRect );
	
	FillListBox(); 
	iListBox->CreateScrollBarFrameL( ETrue );
	iListBox->ScrollBarFrame()->SetScrollBarVisibilityL(CEikScrollBarFrame::EOn, CEikScrollBarFrame::EOn );
	ActivateL();
}
			
 
TInt CExportContactsSelectDirContainer::CountComponentControls() const
{
	return ( int ) ELastControl;
}
  
CCoeControl* CExportContactsSelectDirContainer::ComponentControl( TInt aIndex ) const
{
	 
	switch ( aIndex )
	{
		case EFileInputLabel:
			return iFileInputLabel;
		case EFileInputEdit:
			return iFileInputEdit;
		case EFileExtensionLabel:
			return iFileExtensionLabel;
		case EListBox:
			return iListBox;
	}	 
	return NULL;
}
				
				
void CExportContactsSelectDirContainer::SizeChanged()
{
	CCoeControl::SizeChanged();
	TRect pRect(Rect());
	TInt  pWidth = pRect.Width();
	TInt  pHeight = pRect.Height();
	
	iInputEditRect.SetRect(TPoint( pWidth*0.25, pHeight*0.03 ), TSize( pWidth*0.6, pHeight*0.25 ) );
	
	TSize minisize(iListBox->MinimumSize()) ;	
	TSize uesrDefinedSize(minisize.iWidth,pHeight*0.7);	 	 
	iListBoxRect.SetRect(TPoint( 0, pHeight*0.25 ), uesrDefinedSize);
	
	LayoutControls();
	 
	if(iBgContext)
	{
		iBgContext->SetRect(Rect());
		if ( &Window() )
		{
			iBgContext->SetParentPos( PositionRelativeToScreen() );
		}
	}
	DrawNow();
}
 
void CExportContactsSelectDirContainer::LayoutControls()
{
	TRect pRect(Rect());
	TInt  pWidth = pRect.Width();
	TInt  pHeight = pRect.Height();
	
	iFileInputLabel->SetExtent( TPoint( 0, pHeight*0.05 ), TSize( pWidth*0.25, pHeight*0.25 ) );
	iFileInputEdit->SetExtent(iInputEditRect.iTl, iInputEditRect.Size());	
	iFileExtensionLabel->SetExtent( TPoint( pWidth*0.85, pHeight*0.05 ), TSize( pWidth*0.15, pHeight*0.25 ) ); 
		
	TSize minisize(iListBox->MinimumSize()) ;	
	TSize uesrDefinedSize(minisize.iWidth,pHeight*0.7);	 		 
	iListBox->SetExtent(iListBoxRect.iTl, iListBoxRect.Size());
}

void CExportContactsSelectDirContainer::HandlePointerEventL(const TPointerEvent& aPointerEvent)
{	 
	CCoeControl::HandlePointerEventL(aPointerEvent);
	
	if(iInputEditRect.Contains(aPointerEvent.iPosition))
	{
		iFileInputEdit->HandlePointerEventL(aPointerEvent);		
		
	}else if(iListBoxRect.Contains(aPointerEvent.iPosition))
	{
		iListBox->HandlePointerEventL(aPointerEvent);		
		EnterDir(); 
	}
}	

TKeyResponse CExportContactsSelectDirContainer::OfferKeyEventL( const TKeyEvent& aKeyEvent,TEventCode aType )
{	
	if( aType == EEventKeyUp )
	{		
		switch(aKeyEvent.iScanCode)
	    {			 
		  case EStdKeyDownArrow:
		  {			
			  if(iFocusControl == iFileInputEdit)
			  {
				  return OfferDownKeyEvent(aKeyEvent, aType);
			  }			 		   
		  }
		  break;	
		  case EStdKeyLeftArrow:
		  case EStdKeyRightArrow:
		  {
			if( iFocusControl == iFileInputEdit)
			{
				return iFileInputEdit->OfferKeyEventL(aKeyEvent, aType);
				
			}		
		 }
		  break;		  
		  case EStdKeyHash:
		  {
			  if( iFocusControl == iListBox)
			  {
				EnterDir(); 
				return EKeyWasConsumed;
			  }	
		  }
		  break;
		 default:
		 {
			 if( iFocusControl == iFileInputEdit)
			 {
			 	return iFileInputEdit->OfferKeyEventL(aKeyEvent, aType);			 				
			 }	
		 }
		  break;
	    }
	}else if( aType == EEventKey)
	{
		switch(aKeyEvent.iScanCode)
		{
			case EStdKeyUpArrow:
			{
				if(iFocusControl == iListBox)
				{
					return OfferUpKeyEvent(aKeyEvent, aType);
				}				
			}
			break;
			case EStdKeyDownArrow:
			{
				if(iFocusControl == iListBox)
				{
					return OfferDownKeyEvent(aKeyEvent, aType);
				}				
			}
			case EStdKeyLeftArrow:
			case EStdKeyRightArrow:
			{
				if( iFocusControl == iFileInputEdit)
				{
					return iFileInputEdit->OfferKeyEventL(aKeyEvent, aType);
					
				}		
			}
			break;		
			case EStdKeyDevice3:
		    {
			  if( iFocusControl == iListBox)
			  {
				 EnterDir(); 				 
				 return EKeyWasConsumed;
			  }		
		    }
		    break;
			default:
			{
				if( iFocusControl == iFileInputEdit)
				{
				  return iFileInputEdit->OfferKeyEventL(aKeyEvent, aType);			 				
			    }	
			}
		    break;
		}
	}else if( aType == EEventKeyDown)
	{
		switch(aKeyEvent.iScanCode)
		{
			case EStdKeyLeftArrow:
			case EStdKeyRightArrow:
			{
				if( iFocusControl == iFileInputEdit)
				{
					return iFileInputEdit->OfferKeyEventL(aKeyEvent, aType);
					
				}		
			}
			break;
		   default:
			{
				if( iFocusControl == iFileInputEdit)
				 {
					return iFileInputEdit->OfferKeyEventL(aKeyEvent, aType);			 				
				 }	
			}			
		   break;
		}
	}
	return CCoeControl::OfferKeyEventL( aKeyEvent, aType );
}
	
TKeyResponse CExportContactsSelectDirContainer::OfferUpKeyEvent(const TKeyEvent& aKeyEvent, TEventCode aType)
{
	CTextListBoxModel* model = iListBox->Model();
	TKeyResponse  pKeyResponse;
	
	if(iFocusControl == iListBox)
	{
		if( model->NumberOfItems()>0 )
		{
			TInt pIndex = iListBox->CurrentItemIndex();
			if(pIndex == 0)
			{
				iFocusControl = iFileInputEdit;				
				iFileInputEdit->SelectAllL();	
				iListBox->SetFocus(EFalse);
				iFileInputEdit->SetFocus(ETrue);
				return EKeyWasConsumed;
			}
			else 
			{
				iFocusControl = iListBox;			
				pKeyResponse  = iListBox->OfferKeyEventL( aKeyEvent, aType );
				TInt pSelectedItemIndex = iListBox->CurrentItemIndex();	
				
				 if(iDirLinkList)
				 {
					CDirNode* pTempDirNode = iDirLinkList->Current();
					if(pTempDirNode)
					{
						RPointerArray<TEntry>& pEntryArray = pTempDirNode->GetEntryArray();
						TEntry* pEntry = pEntryArray[pSelectedItemIndex];
						if(pEntry)
						{
							if(pEntry->IsDir())
							{
								iParse.Set(pEntry->iName,NULL,NULL);
							}					
						}				
					}
				 }    			
				iFileInputEdit->SetFocus(EFalse);
				iListBox->SetFocus(ETrue,EDrawNow); 
				return pKeyResponse;
			}
		} 					 
	}else if(iFocusControl == iFileInputEdit)
	{
		return iFileInputEdit->OfferKeyEventL( aKeyEvent, aType );
	}
}

TKeyResponse CExportContactsSelectDirContainer::OfferDownKeyEvent(const TKeyEvent& aKeyEvent, TEventCode aType)
{	
	TKeyResponse  pKeyResponse;
	if(iFocusControl == iFileInputEdit)
    {
	   iFocusControl = iListBox;	
	   iFileInputEdit->SetFocus(EFalse);
	   iListBox->SetFocus(ETrue,EDrawNow);
	   iListBox->SetCurrentItemIndex(0);   
	   pKeyResponse  = iListBox->OfferKeyEventL( aKeyEvent, aType );
	   return pKeyResponse;
	   
    }else if(iFocusControl == iListBox)
	{		  
	    pKeyResponse  = iListBox->OfferKeyEventL( aKeyEvent, aType );	      
		return pKeyResponse;
	}		
}
	
 				
void CExportContactsSelectDirContainer::InitializeControlsL()
{
	CExportContactsAppUi* appUi = (CExportContactsAppUi*)(iEikonEnv->AppUi());
	
	//FileInputLabel
	iFileInputLabel = new ( ELeave ) CEikLabel;
	iFileInputLabel->SetContainerWindowL( *this );	  
	{
	TResourceReader reader;
	iEikonEnv->CreateResourceReaderLC( reader, R_EXPORT_CONTACTS_FILE_INPUT_CONTAINER_FILE_INPUT_LABEL );
	iFileInputLabel->ConstructFromResourceL( reader );
	CleanupStack::PopAndDestroy();  
	}	 
	if(appUi->IsSv5System())
	{
		iFileInputLabel->OverrideColorL( EColorLabelText, KRgbWhite );	 
		iFileInputLabel->OverrideColorL(EColorControlBackground, KRgbBlack );
	}
	
	//FileInputEdit
	iFileInputEdit = new ( ELeave ) CEikEdwin;
	iFileInputEdit->SetContainerWindowL( *this );	 
	{
	TResourceReader reader;
	iEikonEnv->CreateResourceReaderLC( reader, R_EXPORT_CONTACTS_FILE_INPUT_CONTAINER_FILE_INPUT_EDIT );
	iFileInputEdit->ConstructFromResourceL( reader );
	CleanupStack::PopAndDestroy();   
	}
	
	HBufC* text = StringLoader::LoadLC( R_EXPORT_CONTACTS_FILE_INPUT_CONTAINER_FILE_INPUT_EDIT_2 );
	iFileInputEdit->SetTextL( text );
	CleanupStack::PopAndDestroy( text ); 
	
	iFileInputEdit->SetFocus( ETrue );
	iFocusControl = iFileInputEdit;
	
	//FileExtensionLabel
	iFileExtensionLabel = new ( ELeave ) CEikLabel;
	iFileExtensionLabel->SetContainerWindowL( *this );	
	
	{
		TResourceReader reader;
		iEikonEnv->CreateResourceReaderLC( reader, R_EXPORT_CONTACTS_FILE_INPUT_CONTAINER_FILE_EXTENSION_LABEL );
		iFileExtensionLabel->ConstructFromResourceL( reader );
		CleanupStack::PopAndDestroy();  
	}
	if(appUi->IsSv5System())
	{
		iFileExtensionLabel->OverrideColorL( EColorLabelText, KRgbWhite );	 
		iFileExtensionLabel->OverrideColorL(EColorControlBackground, KRgbBlack );
	}	
	
	//Dir Listbox
	iListBox = new ( ELeave ) CAknSingleGraphicStyleListBox;
	iListBox->SetContainerWindowL( *this );
	{
		TResourceReader reader;
		iEikonEnv->CreateResourceReaderLC( reader, R_EXPORT_CONTACTS_SELECT_DIR_LIST_BOX_LIST_BOX );
		iListBox->ConstructFromResourceL( reader );
		CleanupStack::PopAndDestroy();  
	}
	
	iListBox->Model()->SetOwnershipType( ELbmOwnsItemArray );	 
	SetupListBoxIconsL();	  
}
 

 
void CExportContactsSelectDirContainer::HandleResourceChange( TInt aType )
{
	CCoeControl::HandleResourceChange( aType );
	SetRect( iAvkonViewAppUi->View( TUid::Uid( EExportContactsSelectDirContainerViewId ) )->ClientRect() );	
}
				
 			
void CExportContactsSelectDirContainer::Draw( const TRect& aRect ) const
{ 
	CWindowGc& gc = SystemGc();
	gc.Clear( aRect );	 
	MAknsSkinInstance* skin = AknsUtils::SkinInstance();
    MAknsControlContext* cc = AknsDrawUtils::ControlContext( this );
    AknsDrawUtils::Background( skin, cc, this, gc,aRect);
}				
 
void CExportContactsSelectDirContainer::AddListBoxItemL( CEikTextListBox* aListBox,const TDesC& aString )
{
	CTextListBoxModel* model = aListBox->Model();
	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
	itemArray->AppendL( aString );
	aListBox->HandleItemAdditionL();
}
 
RArray< TInt >* CExportContactsSelectDirContainer::GetSelectedListBoxItemsLC( CEikTextListBox* aListBox )
{
	CAknFilteredTextListBoxModel* model = static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() );
	if ( model->NumberOfItems() == 0 )
	{
		return NULL;
	}	
	 
	const CListBoxView::CSelectionIndexArray* selectionIndexes = aListBox->SelectionIndexes();
	TInt selectedIndexesCount = selectionIndexes->Count();
	if ( selectedIndexesCount == 0 )
	{
		return NULL;		
	}	 
	RArray<TInt>* orderedSelectedIndices = 	new (ELeave) RArray< TInt >( selectedIndexesCount );	 
	CleanupStack::PushL( orderedSelectedIndices ); 
	CleanupClosePushL( *orderedSelectedIndices );	
	 
	CAknListBoxFilterItems* filter = model->Filter();
	if ( filter != NULL )
	{		 
		for ( TInt idx = 0; idx < selectedIndexesCount; idx++ )
		{
			TInt filteredItem = ( *selectionIndexes ) [ idx ];
			TInt actualItem = filter->FilteredItemIndex ( filteredItem );
			orderedSelectedIndices->InsertInOrder( actualItem );
		}
	}
	else
	{
	 
		for ( TInt idx = 0; idx < selectedIndexesCount; idx++ )
			orderedSelectedIndices->InsertInOrder( ( *selectionIndexes ) [ idx ] );
	}			
	return orderedSelectedIndices;
}

 
void CExportContactsSelectDirContainer::DeleteSelectedListBoxItemsL( CEikTextListBox* aListBox )
{
	CAknFilteredTextListBoxModel* model = static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() );
	if ( model->NumberOfItems() == 0 )
	{
		return;
	}	
	RArray< TInt >* orderedSelectedIndices = GetSelectedListBoxItemsLC( aListBox );		
	if ( !orderedSelectedIndices )
	{
		return;
	} 
	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
	TInt currentItem = 0;
	
	for ( TInt idx = orderedSelectedIndices->Count(); idx-- > 0; ) 
	{
		currentItem = ( *orderedSelectedIndices )[ idx ];
		itemArray->Delete ( currentItem );
	} 
	CleanupStack::PopAndDestroy();	 
	CleanupStack::PopAndDestroy( orderedSelectedIndices );	 
	AknListBoxUtils::HandleItemRemovalAndPositionHighlightL(aListBox, currentItem, ETrue );
}

void CExportContactsSelectDirContainer::DeleteAllListBoxItemsL( CEikTextListBox* aListBox )
{
	CAknFilteredTextListBoxModel* model = static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() );
	if ( model->NumberOfItems() == 0 )
	{
		return;
	}		 
	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );		
	
	TInt pCount = itemArray->Count();
	for ( TInt idx = pCount-1; idx >= 0;idx-- ) 
	{		 
		itemArray->Delete ( idx );		 
		aListBox->HandleItemRemovalL();
	} 	 	 
}

CAknSingleGraphicStyleListBox* CExportContactsSelectDirContainer::ListBox()
{
	return iListBox;
}
 
void CExportContactsSelectDirContainer::CreateListBoxItemL( TDes& aBuffer, TInt aIconIndex,const TDesC& aMainText )
{
	_LIT ( KStringHeader, "%d\t%S" );	
	aBuffer.Format( KStringHeader(), aIconIndex, &aMainText );
} 
				
 
void CExportContactsSelectDirContainer::AddListBoxResourceArrayItemL( TInt aResourceId, TInt aIconIndex )
{
	CDesCArray* array = iCoeEnv->ReadDesCArrayResourceL( aResourceId );
	CleanupStack::PushL( array ); 
	TBuf<512> listString; 
	CreateListBoxItemL( listString, aIconIndex, ( *array ) [ 0 ] );
	AddListBoxItemL( iListBox, listString );
	CleanupStack::PopAndDestroy( array );
} 
				
 
void CExportContactsSelectDirContainer::SetupListBoxIconsL()
{
	CArrayPtr< CGulIcon >* icons = NULL;		
	icons = new (ELeave) CAknIconArray( 1 );
	CleanupStack::PushL( icons );
	CGulIcon* icon;
	 
	icon = LoadAndScaleIconL(KExportContactsFile, 
							 EMbmExportcontactsList_icon, 
							 EMbmExportcontactsList_icon_mask,
							 NULL, EAspectRatioPreserved );
	CleanupStack::PushL( icon );
	icons->AppendL( icon );
	CleanupStack::Pop( icon );
	CleanupStack::Pop( icons );
	
	if ( icons != NULL )
	{
		iListBox->ItemDrawer()->ColumnData()->SetIconArray( icons );
	}
}

 
TBool CExportContactsSelectDirContainer::HandleMarkableListCommandL( TInt aCommand )
{
	return EFalse;
}

 
CGulIcon* CExportContactsSelectDirContainer::LoadAndScaleIconL( 
		const TDesC& aFileName,
		TInt aBitmapId, 
		TInt aMaskId, 
		TSize* aSize, 
		TScaleMode aScaleMode )
{
	CFbsBitmap* bitmap;
	CFbsBitmap* mask;
	AknIconUtils::CreateIconL( bitmap, mask, aFileName, aBitmapId, aMaskId );
	
	TSize size;
	if ( aSize == NULL )
		{
		 
		AknIconUtils::PreserveIconData( bitmap );
		AknIconUtils::GetContentDimensions( bitmap, size );
		}
	else
		{
		size = *aSize;
		}
	
	AknIconUtils::SetSize( bitmap, size, aScaleMode );
	AknIconUtils::SetSize( mask, size, aScaleMode );
	
	if ( aSize == NULL )
		{
		AknIconUtils::DestroyIconData( bitmap );
		}
	
	return CGulIcon::NewL( bitmap, mask );
}

TTypeUid::Ptr CExportContactsSelectDirContainer::MopSupplyObject(TTypeUid aId)
{
    if (iBgContext )
    {
        return MAknsControlContext::SupplyMopObject( aId, iBgContext );
    }
    return CCoeControl::MopSupplyObject(aId);
}

TBool CExportContactsSelectDirContainer::BackToSuperiorDir()
{			
	CDirNode* pCurrentDirNode = iDirLinkList->Current();
	if(pCurrentDirNode != iDirLinkList->Head())
	{
		iDirLinkList->DeleteNode();
		FillListBox();
		return ETrue;
	}else
	{
		return EFalse;
	}
	
}


TBool CExportContactsSelectDirContainer::EnterDir()
{
	TInt pSelectedItemIndex = iListBox->CurrentItemIndex();	    
	if(iDirLinkList)
	{
		CDirNode* pTempDirNode = iDirLinkList->Current();
		if(pTempDirNode)
		{
			RPointerArray<TEntry>& pEntryArray = pTempDirNode->GetEntryArray();
			TInt pEntryCount = pEntryArray.Count();
			if(pEntryCount>0)
			{
				if(pSelectedItemIndex>=0)
				{
					TEntry* pEntry = pEntryArray[pSelectedItemIndex];
					if(pEntry)
					{
#ifdef Write_Log
{    
	HBufC8* lofBuf = HBufC8::NewL(50);	 
	TPtr8    ptr8(lofBuf->Des()); 
	ptr8.Append(_L8("Before if(pEntry->IsDir())  "));
	ptr8.Append(pEntry->iName);
	WriteToLog(ptr8);
	delete lofBuf;
}
#endif
						if( pEntry->IsDir()
						 || pEntry->iName.Compare(KPhoneDisk)==0
						 || pEntry->iName.Compare(KMemoryCardDisk)==0)
						{
#ifdef Write_Log
{    
	HBufC8* lofBuf = HBufC8::NewL(50);	 
	TPtr8    ptr8(lofBuf->Des()); 
	ptr8.Append(_L8("After if(pEntry->IsDir())"));
	WriteToLog(ptr8);
	delete lofBuf;
}
#endif
							CDirNode* pTempNode = new(ELeave) CDirNode();
							
							HBufC* path = HBufC::NewL(100);
							TPtr ptr(path->Des());
							ptr.Append(pTempDirNode->iParse->FullName());								
						 				
							ptr.Append(pEntry->iName);				
							
							if(ptr.Length()>0)
							{
								TBuf<5> buf;
								buf.Append(ptr.Right(1));
								
								if( buf.Compare(KSlash)!=0)
								{
									ptr.Append(KSlash);
								}
							}			
							pTempNode->iParse->Set(ptr,NULL,NULL);
#ifdef Write_Log
{
	HBufC8* lofBuf = HBufC8::NewL(ptr.Length()*3);	
	TPtr8    ptr8(lofBuf->Des());
	CnvUtfConverter::ConvertFromUnicodeToUtf8(ptr8,ptr);
	WriteToLog(ptr8);
}
#endif
							ReadDir(ptr,KEntryAttDir);							
							if(iDir)
							{
								TInt pCount = iDir->Count();
								if(pCount>0)
								{
									for(TInt item= 0;item<pCount;item++)
									{
										TEntry* pEntry = new(ELeave) TEntry((*iDir)[item]);
										pTempNode->AppendEntry(*pEntry);
									}
								}						
							}									 
							iDirLinkList->AppendNode(*pTempNode);		
							delete path;
						}
					}				
				}
				
			}			
		}
	}     
	FillListBox(); 
}

void  CExportContactsSelectDirContainer::SetParse()
{
	TInt pSelectedItemIndex = iListBox->CurrentItemIndex();		
	if(iDirLinkList)
	{
		CDirNode* pCurrentNode = iDirLinkList->Current();
		CDirNode* pHeadNode = iDirLinkList->Head();		
		if(pCurrentNode)
		{
			if(pCurrentNode == pHeadNode)
			{
				if(pSelectedItemIndex == EPhoneDrive)
				{
					iParse.Set(KPhoneDisk,NULL,NULL);			
				
				}else if(pSelectedItemIndex == EMemoryCardDrive)
				{
					iParse.Set(KMemoryCardDisk,NULL,NULL);					
				}
			}
			else
			{
				iParse.Set(pCurrentNode->iParse->FullName(),NULL,NULL);
				RPointerArray<TEntry>& pEntryArray = pCurrentNode->GetEntryArray();
				TInt pEntryCount = pEntryArray.Count();
				
				if(pEntryCount>0)
				{
					if(pSelectedItemIndex>=0)
					{
						TEntry* pEntry = pEntryArray[pSelectedItemIndex];
						if(pEntry)
						{
							if(pEntry->IsDir())
							{
								iParse.AddDir(pEntry->iName);
							}
						}
					}			
				}			
			}			
		}
	}	
}

TDesC&  CExportContactsSelectDirContainer::GetExportFileFullName()
{
	if(iExportFileFullName)
	{
		delete iExportFileFullName;
	}
	
	SetParse();
	
	TInt pPathLength = iParse.FullName().Length();
	
	HBufC* pEditText = iFileInputEdit->GetTextInHBufL();
	TInt pExportFileLength = pEditText->Length();	
	iExportFileFullName = HBufC::NewL(pPathLength + pExportFileLength + KExportFileExtensionLength);
	TPtr ptr(iExportFileFullName->Des());
	ptr.Append(iParse.FullName());
	ptr.Append(*pEditText);
	ptr.Append(KExportFileExtension);
	
	delete pEditText;
	return *iExportFileFullName;
}

TBool CExportContactsSelectDirContainer::OpenDir(const TDesC &aMatchName, TUint anAttMask)
{
	RDir dir;
	TInt result = dir.Open(iFs,aMatchName,KEntryAttNormal);
    if(result < KErrNone )
	{
    	return EFalse;
	}
    dir.Close();
    return ETrue;
}

TBool CExportContactsSelectDirContainer::ReadDir(const TDesC &aMatchName,TUint anAttMask )
{ 
	if(iDir)
	{
		delete iDir;		 
	}
	iFs.GetDir(aMatchName,anAttMask,ESortByName,iDir);
	return ETrue;
}

void CExportContactsSelectDirContainer::RefreshDir()
{
//	ReadDir(iParse.FullName(),KEntryAttDir);
    FillListBox(); 
}


void CExportContactsSelectDirContainer::MakeDir(const TDesC &aDirName)
{
	TInt pSelectedItemIndex = iListBox->CurrentItemIndex();		
	if(iDirLinkList)
	{
		CDirNode* pCurrentNode = iDirLinkList->Current();
		CDirNode* pHeadNode = iDirLinkList->Head();		
		if(pCurrentNode)
		{
			if(pCurrentNode == pHeadNode)
			{
				if(pSelectedItemIndex == EPhoneDrive)
				{
					iParse.Set(KPhoneDisk,NULL,NULL);			
				
				}else if(pSelectedItemIndex == EMemoryCardDrive)
				{
					iParse.Set(KMemoryCardDisk,NULL,NULL);					
				}
			}
			else
			{
				iParse.Set(pCurrentNode->iParse->FullName(),NULL,NULL);			 
			}			
		}
	}	
	HBufC* path = HBufC::NewL(200);
	TPtr ptr(path->Des());
 	
	ptr.Append(iParse.FullName());
	ptr.Append(aDirName);	
	ptr.Append(KSlash);
	TInt pResult = iFs.MkDir(ptr);
	
	if( pResult == KErrAlreadyExists )
	{
		HBufC* pErrorBuf = StringLoader::LoadLC(R_EXPORT_CONTACTS_SELECT_DIR_MAKE_NEW_ALEADY_EXITS);
		if(pErrorBuf)
		{
			RunGlobalNote(pErrorBuf);
		}
		CleanupStack::PopAndDestroy(pErrorBuf);	
		
	}else  if(pResult != KErrNone)
	{
		HBufC* pErrorBuf = StringLoader::LoadLC(R_EXPORT_CONTACTS_SELECT_DIR_MAKE_NEW_FAIL);
		if(pErrorBuf)
		{
			RunGlobalNote(pErrorBuf);
		}
		CleanupStack::PopAndDestroy(pErrorBuf);	
		
	}else if(pResult == KErrNone)
	{		 
		TEntry* pEntry = new(ELeave) TEntry();		
		TPtr ptr(pEntry->iName.Des());
		ptr.Append(aDirName);
		
		CDirNode* pTempNode = iDirLinkList->Current();
		if(pTempNode)
		{
			if(pTempNode != iDirLinkList->Head())
			{
				RPointerArray<TEntry> *pEntryArray = &(pTempNode->GetEntryArray());
				pEntryArray->Append(pEntry);
			}
		}
		RefreshDir();
	}
	delete  path;
}
void CExportContactsSelectDirContainer::RunGlobalNote( const TDesC* aOverrideText )
{
	CAknGlobalNote* globalNote = CAknGlobalNote::NewLC();
	globalNote->ShowNoteL( EAknGlobalErrorNote, *aOverrideText );	 
	CleanupStack::PopAndDestroy( globalNote );
}

void CExportContactsSelectDirContainer::FillListBox()
{
	DeleteAllListBoxItemsL(iListBox);	 
	
	CDirNode* pTempNode = iDirLinkList->Current();
	if(pTempNode )
	{
		if(pTempNode != iDirLinkList->Head())
		{
			RPointerArray<TEntry> pEntryArray = pTempNode->GetEntryArray();
			TInt pCount = pEntryArray.Count();
			if(pCount>0)
			{
				for(TInt item = 0;item<pCount;item++)
				{
					TEntry* pEntry = pEntryArray[item];
					TBuf<512> listString; 
					CreateListBoxItemL( listString, EListBoxFirstUserImageIndex,pEntry->iName );
					AddListBoxItemL( iListBox,listString );		
				}				
			}
		}else
		{
			AddListBoxResourceArrayItemL( R_EXPORT_CONTACTS_SELECT_DIR_LIST_BOX_LISTBOX_PHONE_ITEM,	EListBoxFirstUserImageIndex );
				
#ifndef __WINS__ 
			if(OpenDir(KMemoryCardDisk,KEntryAttNormal))
//			if(IfMMCCard())
#else
			if(OpenDir(KDDriver,KEntryAttNormal))
//			if(IfMMCCard())
#endif
			{
				AddListBoxResourceArrayItemL( R_EXPORT_CONTACTS_SELECT_DIR_LIST_BOX_LISTBOX_MEMORY_ITEM, EListBoxFirstUserImageIndex );	
			}				 
		}		
		iListBox->SetCurrentItemIndex(0);
		iListBox->HandleItemAdditionL();
	}  
}

void  CExportContactsSelectDirContainer::InitializeLinkList()
{
	iDirLinkList = CDirLinkList::NewL();	
	CDirNode* pTempNode = new(ELeave) CDirNode();	
	 
	TEntry*   pTempEntry = new(ELeave) TEntry();	
	TPtr ptrC(pTempEntry->iName.Des());
	ptrC.Copy(KPhoneDisk);
	pTempNode->AppendEntry(*pTempEntry); 
 
	if(IfMMCCard())
	{
		pTempEntry = new(ELeave) TEntry();	
		TPtr ptrE(pTempEntry->iName.Des());
		ptrE.Copy(KMemoryCardDisk);
		pTempNode->AppendEntry(*pTempEntry);
		TBool isDir =  pTempEntry->IsDir();	 
	}	
		
#ifdef Write_Log
{    
	HBufC8* lofBuf = HBufC8::NewL(50);	 
	TPtr8    ptr8(lofBuf->Des()); 
	ptr8.Append(_L8("InitializeLinkList  "));
	ptr8.Append(pTempEntry->iName);
	ptr8.Append(_L8("IsDir:  "));
	ptr8.AppendNum(isDir);
	WriteToLog(ptr8);
	delete lofBuf;
}
#endif

	pTempNode->iParse->Set(KNullDesC,NULL,NULL);
	iDirLinkList->AppendNode(*pTempNode);		 
}

TBool CExportContactsSelectDirContainer::IfMMCCard()
{
	RFs  fileSvrSession;
	User::LeaveIfError(fileSvrSession.Connect());
	
	TDriveList  pDriveList;
	fileSvrSession.DriveList(pDriveList);
	
    if (!pDriveList[EDriveE]) //如果MMC卡不存在 
	{ 
		fileSvrSession.Close();
		return EFalse;
	}
//  TBuf<10> pDriveName;
//  fileSvrSession.GetDriveName(EDriveE, pDriveName);
    fileSvrSession.Close();
    return ETrue;
 }


void CExportContactsSelectDirContainer::ChangeCBA()
{
	CEikButtonGroupContainer* cba =CEikButtonGroupContainer::Current();
	if(iParse.IsRoot())
	{
		cba->SetCommandSetL(R_AVKON_SOFTKEYS_OPTIONS_EXIT);
	}else
	{
		cba->SetCommandSetL(R_AVKON_SOFTKEYS_OPTIONS_BACK);
	}	
	cba->DrawNow();
}

void CExportContactsSelectDirContainer::WriteToLog(const TDesC8& aDesC)
{
	RFs fileSession; 
	User::LeaveIfError(fileSession.Connect());
	CleanupClosePushL(fileSession);
	
	RFile file; 
	TInt error = file.Open(fileSession,KFileName,EFileWrite);
	CleanupClosePushL(file); 
	
	if(error == KErrNone)
	{
		TInt fileSize;
		file.Size(fileSize);
		file.Write(fileSize,aDesC);
	
	}else 
	{
		file.Replace(fileSession,KFileName,EFileWrite);
		file.Write(aDesC);	
	}
	CleanupStack::PopAndDestroy(2);
}
//End of file
 
